﻿using System;
using System.Collections.Generic;
using System.Text;
using BingZi.HY.Core.Enums;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Web;
using System.Reflection;

namespace BingZi.HY.Core.WebCommon
{
    /// <summary>
    /// 网页工具类
    /// </summary>
    public  class WebHelper 
    {
        #region HTML字符串缩略方法
        private const int N_STRINGRESTRIC_Length = 14;
        /// <summary>
        ///  HTML字符串缩略方法
        /// </summary>
        /// <param name="strVal">需要缩略的字符串</param>
        /// <returns>缩略后的结果(String...)</returns>
        public static string StringRestric(string strVal)
        {
            return WebHelper.StringRestric(strVal, N_STRINGRESTRIC_Length);
        }

        /// <summary>
        /// HTML字符串缩略方法
        /// </summary>
        /// <param name="strVal">需要缩略的字符串</param>
        /// <param name="len">缩略起始索引</param>
        /// <returns>缩略后的结果(String...)</returns>
        public static string StringRestricSub(string strVal, int len)
        {
            string result = "";

            string strDecode = HttpUtility.HtmlDecode(strVal);

            if (strDecode != null && strDecode.Length > len)
            {
                if (strDecode.Length > 300)
                {
                    result = "<span title=\"" + strVal.Substring(0, 300) + "..." + "\">" + strDecode.Substring(0, len) + "...</span>";
                }
                else
                {
                    result = "<span title=\"" + strVal + "\">" + strDecode.Substring(0, len) + "...</span>";
                }
            }
            else
            {
                result = strDecode;
            }

            return result;
        }

        /// <summary>
        /// HTML字符串缩略方法
        /// </summary>
        /// <param name="strVal">需要缩略的字符串</param>
        /// <param name="len">缩略起始索引</param>
        /// <returns>缩略后的结果(String...)</returns>
        public static string StringRestric(string strVal, int len)
        {
            string result = "";

            string strDecode = HttpUtility.HtmlDecode(strVal);

            //if (strDecode != null && strDecode.Length > len)
            //{
            result = string.Concat("<span class='spanBreak' title='", strVal, "' style='width:", 0, "px;'>", strVal, "</span>");
            //if (strDecode.Length > 300)
            //{
            //    result = "<span title=\"" + strVal.Substring(0, 300) + "..." + "\">" + strDecode.Substring(0, len) + "...</span>";
            //}
            //else
            //{
            //    result = "<span title=\"" + strVal + "\">" + strDecode.Substring(0, len) + "...</span>";
            //}
            //}
            //else
            //{
            //    result = strDecode;
            //}

            return result;
        }

        /// <summary>
        /// HTML字符串缩略方法
        /// </summary>
        /// <param name="strVal">需要缩略的字符串</param>
        /// <param name="len">缩略起始索引</param>
        /// <returns>缩略后的结果(String...)</returns>
        public static string StringRestric(string strVal, int len, int leftWidth)
        {
            string result = "";
            string strDecode = HttpUtility.HtmlDecode(strVal);
            result = string.Concat("<span class='spanBreak' title='", strVal, "' leftwidth='", leftWidth, "' style='width:", 0, "px;'>", strVal, "</span>");
            return result;
        }
        /// <summary>
        /// HTML字符串缩略方法
        /// </summary>
        /// <param name="strVal">需要缩略的字符串</param>
        /// <param name="len">缩略起始索引</param>
        /// <param name="title">指定提示信息</param>
        /// <returns>缩略后的结果(String...)</returns>
        public static string StringRestric(string strVal, int len, string title)
        {
            string result = "";

            string strDecode = HttpUtility.HtmlDecode(strVal);

            if (strDecode != null && strDecode.Length > len)
            {
                string tempStr = String.Empty;
                if (title.Length > 300)
                {
                    tempStr = strDecode.Substring(0, len);
                    if (tempStr.LastIndexOf('<') <= tempStr.LastIndexOf('>'))
                    {
                        result = "<span title=\"" + title.Substring(0, 300) + "..." + "\">" + tempStr + "...</span>";
                    }
                    else
                    {
                        tempStr = tempStr.Substring(0, tempStr.LastIndexOf('<'));
                        result = "<span title=\"" + title.Substring(0, 300) + "..." + "\">" + tempStr + "...</span>";
                    }
                }
                else
                {
                    tempStr = strDecode.Substring(0, len);
                    if (tempStr.LastIndexOf('<') <= tempStr.LastIndexOf('>'))
                    {
                        result = "<span title=\"" + title + "\">" + tempStr + "...</span>";
                    }
                    else
                    {
                        tempStr = tempStr.Substring(0, tempStr.LastIndexOf('<'));
                        result = "<span title=\"" + title + "\">" + tempStr + "...</span>";
                    }
                }
            }
            else
            {
                result = strDecode;
            }

            return result;
        }
        #endregion

        #region HTML字符串换行方法
        private const int N_AutoBreakWordLength = 120;
        /// <summary>
        /// HTML字符串换行方法
        /// </summary>
        /// <param name="str">需要自动换行字符串</param>
        /// <returns>返回自动换行后的值</returns>
        public static string AutoBreakWord(string str)
        {
            return AutoBreakWord(str, N_AutoBreakWordLength);
        }

        /// <summary>
        ///  HTML字符串换行方法      
        /// </summary>
        /// <param name="str">需要自动换行字符串</param>
        /// <param name="length">位数</param>
        /// <returns>返回自动换行后的值</returns>
        public static string AutoBreakWord(string str, int length)
        {
            if ((str == null) || (str == ""))
                return str;
            str = str.Replace("\r", "");
            int nSpaceIndex = str.IndexOf(" ");
            int nLastIndex = str.LastIndexOf("\n");
            int nLength = str.Length;
            StringBuilder sbResult = new StringBuilder();
            string[] straStr = str.Split(new string[1] { "\n" }, StringSplitOptions.None);
            if (straStr.Length > 0)
            {
                if (nSpaceIndex > 0 || nLastIndex > 0)
                {
                    bool IsEnter = true;
                    for (int m = 0; m < straStr.Length; m++)
                    {
                        if (straStr[m].Length > length)
                        {
                            int count = straStr[m].Length / length;
                            for (int i = 0; i < count; i++)
                            {
                                string strTemp = straStr[m].Substring(i * length, length);
                                int nTempSpaceIndex = strTemp.LastIndexOf(" ");
                                if (nTempSpaceIndex > 0)
                                {
                                    strTemp = strTemp.Insert(nTempSpaceIndex, "\n");
                                    sbResult.Append(strTemp);
                                }
                                else
                                {
                                    sbResult.Append(strTemp);
                                    sbResult.Append("\n");
                                    IsEnter = false;
                                }
                            }
                            if (straStr[m].Length % length != 0)
                            {
                                string strOther = straStr[m].Substring(count * length);
                                if (!IsEnter)
                                {
                                    int nOtherSpaceIndex = strOther.LastIndexOf(" ");
                                    if (nOtherSpaceIndex > 0)
                                        strOther = strOther.Insert(nOtherSpaceIndex, "\n");
                                }
                                sbResult.Append(strOther);
                            }
                        }
                        else
                        {
                            sbResult.Append(straStr[m]);
                        }
                        sbResult.Append("\n");
                    }
                }
                else
                {
                    for (int m = 0; m < straStr.Length; m++)
                    {
                        if (straStr[m].Length > length)
                        {
                            int count = straStr[m].Length / length;
                            for (int i = 0; i < count; i++)
                            {
                                sbResult.Append(straStr[m].Substring(i * length, length))
                                    .Append("\n");
                            }
                            if (straStr[m].Length % length != 0)
                            {
                                sbResult.Append(straStr[m].Substring(count * length));
                            }
                        }
                        else
                        {
                            sbResult.Append(straStr[m]);
                        }
                        sbResult.Append("\n");
                    }
                }
                if (nLastIndex < nLength - 1)
                {
                    sbResult.Remove(sbResult.Length - 1, 1);
                }
            }
            return sbResult.ToString().Replace(" ", "&nbsp;").Replace("\n", "<br>");
        }

        #endregion

        #region 格式相关
        /// <summary>
        ///将字符串文本格式转换为HTML格式
        /// </summary>
        /// <param name="Content">需要转换的文本</param>
        /// <returns>转换后的文本</returns>
        public static string FormatStringToHTML(string Content)
        {
            string text = Content;
            text = text.Replace("<", "&lt;");
            text = text.Replace(">", "&gt;");
            text = text.Replace("'", "''");
            text = text.Replace(" ", "&nbsp;");
            text = text.Replace("\n", "<br/>");
            text = text.Replace("\r\n", "<br/>");
            text = text.Trim();
            return text;

        }

        /// <summary>
        /// 返回指定个数个HTML空格
        /// </summary>
        /// <param name="num">指定个数</param>
        /// <returns>HTML结果</returns>
        public static string GetSpace(int num)
        {
            string space = "";
            for (int i = 0; i < num; i++)
            {
                space += "&nbsp;";
            }
            return space;
        }

        #endregion

        #region 数据绑定方法

        private static void BindList(ListControl list, object dataSource, string textField, string valueField)
        {
            list.DataSource = dataSource;
            list.DataTextField = textField;
            list.DataValueField = valueField;
            list.DataBind();
        }
        private static string FormatUrl(string path)
        {
            if (path[0] == '\\')
            {
                path = path.TrimStart('\\');
            }
            path = path.Replace('\\', '/');
            if (path[path.Length - 1] != '/')
            {
                path += "/";
            }
            return path;
        }

        #region 绑定DropDownList、ListBox等

        /// <summary>
        /// 绑定DropDownList、ListBox等
        /// modify by wsliu
        /// 修改记录：方法内部实现是自己调用自己，为死循环，导致IIS错误
        /// </summary>
        /// <param name="list">控件ID</param>
        /// <param name="dataSource">数据源</param>
        /// <param name="textField">显示的文本字段</param>
        /// <param name="valueField">值字段</param>
        public static void BindList(ListControl list, DataSet dataSource, string textField, string valueField)
        {
            //BindList(list, dataSource, textField, valueField);
            BindList(list, (object)dataSource, textField, valueField);
        }
        /// <summary>
        /// 绑定DropDownList、ListBox等
        /// </summary>
        /// <param name="list"></param>
        /// <param name="dataSource">枚举类型</param>
        public static void BindList(ListControl list, Type dataSource)
        {
            System.Data.DataTable dt = EnumHelper.GetEnumTable(dataSource);

            BindList(list, dt.DefaultView, "Text", "Value");
        }


        /// <summary>
        /// 绑定DropDownList、ListBox等
        /// modify by wsliu
        /// 修改记录：方法内部实现是自己调用自己，为死循环，导致IIS错误
        /// </summary>
        /// <param name="list">控件ID</param>
        /// <param name="dataSource">数据源</param>
        /// <param name="textField">显示的文本字段</param>
        /// <param name="valueField">值字段</param>
        public static void BindList(ListControl list, DataView dataSource, string textField, string valueField)
        {
            //BindList(list, dataSource, textField, valueField);
            BindList(list, (object)dataSource, textField, valueField);
        }


        /// <summary>
        /// 绑定DropDownList、ListBox等
        /// modify by wsliu
        /// 修改记录：方法内部实现是自己调用自己，为死循环，导致IIS错误
        /// </summary>
        /// <param name="list">控件ID</param>
        /// <param name="dataSource">数据源</param>
        /// <param name="textField">显示的文本字段</param>
        /// <param name="valueField">值字段</param>
        public static void BindList(ListControl list, ArrayList dataSource, string textField, string valueField)
        {
            //BindList(list, dataSource, textField, valueField);
            BindList(list, (object)dataSource, textField, valueField);
        }


        /// <summary>
        /// DataList数据绑定, 设置当DataList中的项目数为0时是否自动隐藏该DataList
        /// </summary>
        /// <param name="list">DataList</param>
        /// <param name="dv">DataView</param>
        /// <param name="keyField">绑定的键字段</param>
        /// <param name="sortText">排序表达式</param>
        /// <param name="isAutoHidden">是否自动隐藏</param>
        public static void BindList(DataList list, DataView dv, string keyField,
            string sortText, bool isAutoHidden)
        {
            if (sortText != null)
            {
                dv.Sort = sortText;
            }

            list.DataSource = dv;

            if (keyField != null)
            {
                list.DataKeyField = keyField;
            }

            list.DataBind();

            //如果没有物品则将DataList置为不可见
            if (isAutoHidden)
            {
                if (list.Items.Count < 1)
                {
                    list.Visible = false;
                }
                else
                {
                    list.Visible = true;
                }
            }
        }


        /// <summary>
        /// DataList数据绑定, 默认不自动隐藏
        /// </summary>
        /// <param name="list">DataList</param>
        /// <param name="dv">DataView</param>
        /// <param name="keyField">绑定的键字段</param>
        /// <param name="sortText">排序表达式</param>
        public static void BindList(DataList list, DataView dv, string keyField, string sortText)
        {
            BindList(list, dv, keyField, sortText, false);
        }


        #endregion


        #region List 控件的赋值取值，包括可以多选的List控件


        /// <summary>
        /// Help to set value to be selected
        /// </summary>
        /// <param name="list">list control</param>
        /// <param name="value">value</param>
        public static void SelectedListByValue(ListControl list, object value)
        {
            if (value == DBNull.Value || value == null)
            {
                list.SelectedIndex = -1;
            }
            else
            {
                list.SelectedIndex = list.Items.IndexOf(list.Items.FindByValue(value.ToString()));
            }
        }


        /// <summary>
        /// Help to set value to be selected
        /// </summary>
        /// <param name="list">list control</param>
        /// <param name="text">text</param>
        public static void SelectedListByText(ListControl list, string text)
        {
            list.SelectedIndex = -1;
            list.SelectedIndex = list.Items.IndexOf(list.Items.FindByText(text.ToString()));
        }

        /// <summary>
        /// 获取列表控件被多项选择的文本和值，文本格式为“a,b,c,d”，值格式为“1,2,3,4”
        /// </summary>
        /// <param name="list"></param>
        /// <param name="textStr"></param>
        /// <param name="idStr"></param>
        public static void GetSelected(ListControl list, out string textStr, out string idStr)
        {
            textStr = "";
            idStr = ",";
            foreach (ListItem item in list.Items)
            {
                if (item.Selected)
                {
                    textStr += item.Text + ",";
                    idStr += item.Value + ",";
                }
            }
            if (textStr.Length > 0)
            {
                textStr = textStr.TrimEnd(',');
            }
        }


        /// <summary>
        /// 根据值的字符串，选定多个项目
        /// alert by huzhang 2006-1-5
        /// </summary>
        /// <param name="list"></param>
        /// <param name="value">值格式为“1,2,3,4”</param>
        public static void SelectedListMultiByValue(ListControl list, string value)
        {
            if (IsNotNull(value))
            {
                list.SelectedIndex = -1;
                value = "," + value + ",";
                string strSelected;
                foreach (ListItem item in list.Items)
                {
                    strSelected = "," + item.Value + ",";
                    if (value.IndexOf(strSelected) > -1)
                    {
                        item.Selected = true;
                        value.Replace(strSelected, ",");
                        if (value == ",")
                            break;
                    }
                }
            }
        }


        /// <summary>
        /// 根据值的字符串，选定多个项目
        /// </summary>
        /// <param name="list"></param>
        /// <param name="value"></param>
        /// <param name="splitFlag"></param>
        public static void SelectedListMultiByValue(ListControl list, string value, string splitFlag)
        {
            if (IsNotNull(value))
            {
                list.SelectedIndex = -1;
                value = splitFlag + value + splitFlag;
                string strSelected;
                foreach (ListItem item in list.Items)
                {
                    strSelected = splitFlag + item.Value + splitFlag;
                    if (value.IndexOf(strSelected) > -1)
                    {
                        item.Selected = true;
                        value.Replace(strSelected, splitFlag);
                        if (value == splitFlag)
                            break;
                    }
                }
            }
        }

        #endregion


        /// <summary>
        /// 判断时候为空
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNotNull(string str)
        {
            return string.IsNullOrEmpty(str);
        }
        #endregion



        #region Helper Methods

        /// <summary>
        /// Gets the string param.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="paramName">Name of the param.</param>
        /// <param name="errorReturn">The error return.</param>
        /// <returns>The param value.</returns>
        public static string GetStringParam(System.Web.HttpRequest request, string paramName, string errorReturn)
        {
            string retStr = request.Form[paramName];
            if (retStr == null)
            {
                retStr = request.QueryString[paramName];
            }
            if (retStr == null)
            {
                return errorReturn;
            }
            return retStr;
        }

        /// <summary>
        /// Gets the int param.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="paramName">Name of the param.</param>
        /// <param name="errorReturn">The error return.</param>
        /// <returns>The param value.</returns>
        public static int GetIntParam(System.Web.HttpRequest request, string paramName, int errorReturn)
        {
            string retStr = request.Form[paramName];
            if (retStr == null)
            {
                retStr = request.QueryString[paramName];
            }
            if (retStr == null || retStr.Trim() == string.Empty)
            {
                return errorReturn;
            }
            try
            {
                return Convert.ToInt32(retStr);
            }
            catch
            {
                return errorReturn;
            }
        }

        /// <summary>
        /// Gets the date time param.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="paramName">Name of the param.</param>
        /// <param name="errorReturn">The error return.</param>
        /// <returns>The param value.</returns>
        public static DateTime GetDateTimeParam(System.Web.HttpRequest request, string paramName, DateTime errorReturn)
        {
            string retStr = request.Form[paramName];
            if (retStr == null)
            {
                retStr = request.QueryString[paramName];
            }
            if (retStr == null || retStr.Trim() == string.Empty)
            {
                return errorReturn;
            }
            try
            {
                return Convert.ToDateTime(retStr);
            }
            catch
            {
                return errorReturn;
            }
        }

        /// <summary>
        /// Strongs the typed.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns>The strong typed instance.</returns>
        public static ObjectType StrongTyped<ObjectType>(object obj)
        {
            return (ObjectType)obj;
        }

        /// <summary>
        /// Toes the js single quote safe string.
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <returns>The formated str.</returns>
        public static string ToJsSingleQuoteSafeString(string str)
        {
            return str.Replace("'", "\\'");
        }

        /// <summary>
        /// Toes the js double quote safe string.
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <returns>The formated str.</returns>
        public static string ToJsDoubleQuoteSafeString(string str)
        {
            return str.Replace("\"", "\\\"");
        }

        /// <summary>
        /// Toes the VBS quote safe string.
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <returns>The formated str.</returns>
        public static string ToVbsQuoteSafeString(string str)
        {
            return str.Replace("\"", "\"\"");
        }

        /// <summary>
        /// Toes the SQL quote safe string.
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <returns>The formated str.</returns>
        public static string ToSqlQuoteSafeString(string str)
        {
            return str.Replace("'", "''");
        }

        /// <summary>
        /// Texts to HTML.
        /// </summary>
        /// <param name="txtStr">The TXT STR.</param>
        /// <returns>The formated str.</returns>
        public static string TextToHtml(string txtStr)
        {
            return txtStr.Replace(" ", "&nbsp;").Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;").
                Replace("<", "&lt;").Replace(">", "&gt;").Replace("\r", "").Replace("\n", "<br />");
        }

        /// <summary>
        /// 根据字符串，利用“,”分隔获取集合
        /// </summary>
        /// <param name="strs"></param>
        /// <returns></returns>
        public static List<string> GetList(string strs)
        {
            List<string> list = new List<string>();
            if (!string.IsNullOrEmpty(strs))
            {
                strs = strs.Replace("，", ",");
                strs = strs.TrimStart(',').TrimEnd(',');
                string[] strArray = strs.Split(',');
                list.AddRange(strArray);
            }
            return list;
        }
        #endregion
    }
}
